
package com.hongri.recyclerview.service;

import java.util.HashMap;

import android.support.annotation.NonNull;
import com.hongri.recyclerview.https.IHttpRequest;
import com.hongri.recyclerview.interfaceService.HongriInterface;
import com.hongri.recyclerview.interfaceService.HongriManager;

/**
 * 红日功能接口实现类（工厂接口）
 */
public final class HongriServiceImpl extends HongriService {
    private static HashMap<String, Object> services = new HashMap<>();

    private HongriServiceImpl() {
    }


    public synchronized static HongriService getInstance() {
        if (instance == null) {
            instance = new HongriServiceImpl();
        }
        return instance;
    }

    @Override
    protected @NonNull <T> T getServiceImpl(Class<T> clazz) {
        String cn = clazz.getName();
        if (!services.containsKey(cn)) {
            createService(cn);
        }
        if (cn.equals(IHttpRequest.class.getName())) {
            try {
                return (T) (services.get(cn).getClass().newInstance());
            } catch (Exception e) {
                return null;
            }
        }
        return (T) services.get(cn);
    }

    @Override
    protected @NonNull <T> T getServiceImpl(Class<T> clazz, boolean isNeedNewObject) {
        String cn = clazz.getName();
        if (!services.containsKey(cn)) {
            createService(cn);
        }
        if (!isNeedNewObject) {
            return (T) services.get(cn);
        } else {
            try {
                return (T) (services.get(cn).getClass().newInstance());
            } catch (Exception e) {
                return null;
            }
        }
    }

    private void createService(String cName) {
        if (HongriInterface.class.getName().equals(cName)){
            services.put(cName, HongriManager.getInstance());
        }
    }

}
